<?php

namespace app\index\controller;

use think\Controller;

class Count extends Base
{
    public function open_answer()
    {

        $id = input('artid');
        //var_dump($id);exit();
        //$id= 52;
        $loginmember = input('loginmember');
        $serialnumber = input('serialnumber');

        if ($loginmember) {
            //return $this->success('投票成功！','index');

            //session('loginname') = $loginmember;


            $data['member'] = input('loginmember');
            $data['nickname'] = input('loginmember');

            $validate = \think\Loader::validate('openanswer');
            if ($validate->check($data)) {
                // return $this->success('登记成功！开始答题','article/index' );
                //var_dump("ok");
                //exit();
                session('loginmember', "$loginmember");
                session('serialnumber', "$serialnumber");
                return $this->redirect('article/index', ['artid' => $id]);
            } else {
                return $this->error($validate->getError());
            }

        } elseif (input('reset')) {
            # code...
            session('loginmember', " ");
            session('serialnumber', " ");
            //return $this->error('');
            //return $this->success('','article/index', ['artid' => 53]);
            return $this->redirect('article/index', ['artid' => $id]);
        } else {
            return $this->error('请输入姓名');
        }
    }

    public function count()
    {
        $id = input('artid');
        $tomdown = input('d');


        $article_contens = \think\Db::name('article_contens')
            ->where('cate', $id)
            ->order('id')
            ->where('title', 'neq', ' ')
            ->select();

        //var_dump($article_contens);
        //exit();
        //var_dump(count($article_contens));


        // 循环读取所有问题
        for ($a = 0; $a < count($article_contens); $a++) {
            # code...
            //echo $a ."-------------------------------<br/>";
            // 查询出指定问题的回答总数，尝试变量循环
            $honey = 0;
            for ($i = 1; $i < 7; $i++) {
                $arid = $i - 1;
                $count = \think\Db::name('answer')
                    ->where('cate', $id)
                    ->where('answerid', $article_contens[$a]['id'])
                    ->sum('answer' . $i);
                //var_dump($count);

                $a1 = $a + 1;
                $article_contens[$a]['checked' . $i] = $count;
                // $vo.checked{$i}           {$c1} 
                //            问题总数         问题1-6的排序
                //echo $article_contens[$a]['checked'.$i]."<br/>";

                $honey = $honey + $count;
                $son = $i;
                if ($son >= 6) {
                    for ($s = 1; $s < 7; $s++) {
                        if ($honey <= 0) {
                            # code...
                            $article_contens[$a]['checked_son' . $s] = 0;
                        } else {

                            # code...
                            //var_dump(round($article_contens[$a]['checked'.$s]/$honey*100));

                            $article_contens[$a]['checked_son' . $s] = round($article_contens[$a]['checked' . $s] / $honey * 100);
                        }
                    }

                }

            }


            //echo "-------------------------------<br/>";
        }

//dump($article_contens);
//        print_r(array_keys($article_contens['0']));
//        die();
//      关于导出文件的生成和自动下载
        if ($tomdown >= 1) {
            $this->out($id);
            die();
        }
        if ($tomdown == 19) {
            $filename = time();
//          dump($article_contens);

            header("content-type:text/html; charset=utf-8");
            $file = fopen("f-$filename.csv", "w");

//          $line = array(1,'学习—中文乱码',12345,'vb200',iconv("UTF-8", "GB2312//IGNORE", "学习—中文乱码"));
            $title = array('ID', '编号', '问卷题目', 'vb200', '问卷选项');

//            这里是获取字段的名字
            $title = array_keys($article_contens['0']);
            $line = $article_contens;

            //提前设置一个数组，设置导出后标题
            foreach ($title as &$value) {
                $value = iconv("UTF-8", "GB2312//IGNORE", "$value");
            }
            fputcsv($file, $title);
            // 可以去掉某些不需要的数组。
            foreach ($line as $value) {
                foreach ($value as &$valuevalue) {
//                    foreach ($valuevalue as &$s){
                    echo($valuevalue);
//                        echo "$valuevalue <br>";
                    $valuevalue = iconv("UTF-8", "GB2312//IGNORE", "$valuevalue");
//                    die();

//                    }

                }
//                注意这一句的放置位置
                fputcsv($file, $value);
            }

//            die();


            fclose($file);

            echo "f-$filename.csv";
//            redirect('/f-$filename.csv');
            echo url('/', 'id=5');
            $downurl = url('', '');
//            dump(get_defined_constants(true));
//重定向到指定的URL地址 并且使用302
            $PHP_SELF = $_SERVER['PHP_SELF'];

            $url = 'http://' . $_SERVER['HTTP_HOST'];

            dump($url);


            // $this->redirect($url."/gmt/public/f-".$filename.".csv",302);
            $this->redirect($url . "/public/f-" . $filename . ".csv", 302);
            dump("导出成功");


//                die();
        }

        //echo(round(1.98888888888888));exit();


        //->select();


        // 循环赋值
        //var_dump($count);
        //print_r(array_sum($count[0]["answer1"]));

        //var_dump(sum($count));
        //exit();

        //var_dump(count($article_contens));
        //exit();

        if (request()->isPost()) {


            $arts['open'] = "";
            //var_dump(input('post.'));
            $i = 1;
            while ($i <= count($article_contens)) {
                # code...


                if (input('var' . $i) == 'radio') {
                    # code...
                    //var_dump(" i am raido");
                    $radiovalue = input('answer' . $i);
                    //$data['answer'.$radiovalue] = $radiovalue;
                    //var_dump('answer'.$radiovalue);exit;

                    $data = [
                        'answer' . input('answer' . $i) => input('answer' . $i),
                        'cate' => $id,
                        'name' => session('loginmember') . time(),
                        'member' => session('loginmember'),
                        'answerid' => input('answerid' . $i),
                        'serialnumber' => session('serialnumber'),
                        'time' => time(),
                    ];

                    $db = '';
                    if ($radiovalue) {
                        # code...
                        //var_dump($radiovalue); 
                        $db = \think\Db::name('answer')->insert($data);
                        //$db='';
                    } else {

                        return $this->error('第' . $i . '题目未选择');

                    }


                } else {
                    //var_dump("i am checkbox");
                    $data = [
                        'answer1' => input('answer' . $i . '1'),
                        'answer2' => input('answer' . $i . '2'),
                        'answer3' => input('answer' . $i . '3'),
                        'answer4' => input('answer' . $i . '4'),
                        'answer5' => input('answer' . $i . '5'),
                        'answer6' => input('answer' . $i . '6'),
                        'cate' => $id,
                        'member' => session('loginmember'),
                        'name' => session('loginmember') . time(),
                        'answerid' => input('answerid' . $i),
                        'time' => time(),
                        'serialnumber' => session('serialnumber'),
                    ];

                    if (input('answer' . $i . '1') or input('answer' . $i . '2') or input('answer' . $i . '3') or input('answer' . $i . '4') or input('answer' . $i . '5') or input('answer' . $i . '6')) {
                        # code...
                        $db = \think\Db::name('answer')->insert($data);
                    } else {
                        return $this->error('第' . $i . '题目未选择');

                    }
                    # code...


                }


                $i++;
            }

            $validate = \think\Loader::validate('answer');
            if ($validate->check($data)) {

                if ($db) {
                    //return $this->success('投票成功！','index');
                    return $this->success('投票成功！', 'index/select');

                } else {
                    return $this->error('第' . $i . '题目未选择');
                }
            } else {
                return $this->error($validate->getError());
            }

            exit();


        }
        db('article')->where('id', $id)->setInc('click');
        $arts = \think\Db::name('article')->alias('a')->join('cate c', 'c.id = a.cateid', 'LEFT')->field('a.title,a.desc,a.time,a.click,a.close,a.id,a.cateid,c.catename')->where('a.id', $id)->find();
        // $prev= \think\Db::name('article')->where('id','<',$id)->where('cateid','=',$arts['cateid'])->order('id desc')->limit(1)->value('id');
        // $next= \think\Db::name('article')->where('id','>',$id)->where('cateid','=',$arts['cateid'])->order('id asc')->limit(1)->value('id');
        // $ralateres=$this->ralate($arts['keywords']);

        // var_dump($article_contens); die;
        // $arts['opend']= "none";
        // 查询出所有回答的回答总条数，尝试变量循环
        $answer_count = \think\Db::name('answer')
            ->where('cate', $id)
            ->where('answerid', $article_contens[0]['id'])
            ->field('answer1')
            ->count('answer1');

// var_dump($article_contens);exit();
        // var_dump($article_contens);exit();
        $this->assign('arts', $arts);
        // $this->assign('prev',$prev);
        // $this->assign('next',$next);
        // $this->assign('ralateres',$ralateres);
        $this->assign('answer_count', $answer_count);
        // $this->assign('acc',$acc);
        $this->assign('article_contens', $article_contens);

        return $this->fetch('count');
    }

    public function test()
    {
        // 假设你有一个数组或对象
        $data = array(
            'name' => 'John Doe',
            'age' => 30,
            'email' => 'johndoe@example.com'
        );

// 返回JSON数据给前端
        return json($data);
    }


    public function out($article_id)
    {
//        ob_clean();
//        flush();

// 输出Excel文件头，可把user.csv换成你要的文件名
//        header('Content-Type: application/vnd.ms-excel');
//        header('Content-Disposition: attachment;filename="user.csv"');
        header('Cache-Control: max-age=0');
// 从数据库中获取数据，为了节省内存，不要把数据一次性读到内存，从句柄中一行一行读即可

//        $stmt = array('姓名', 'nan', '年龄', 'Email', '电话', '……');
// 打开PHP文件句柄，php://output 表示直接输出到浏览器
        $fp = fopen('php://output', 'a');
// 输出Excel列名信息
//        $head = array('姓名', 'nv', '年龄', 'Email', '电话', '……');
//        foreach ($head as $i => $v) {
//            // CSV的Excel支持GBK编码，一定要转换，否则乱码
//            $head[$i] = iconv('utf-8', 'gbk', $v);
//        }
//        foreach ($stmt as $i => $v) {
//            // CSV的Excel支持GBK编码，一定要转换，否则乱码
//            $stmt[$i] = iconv('utf-8', 'gbk', $v);
//        }
// 将数据通过fputcsv写到文件句柄
//        fputcsv($fp, $head);
// 计数器
        $cnt = 0;
// 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;
// 逐行取出数据，不浪费内存

//                $row  = $stmt;

//            fputcsv($fp, $row);


        $fileName = session('username') . date('_YmdHis');
        header("Content-type:application/vnd.ms-excel;charset=utf-8");
        header("Content-Disposition:attachment;filename=$fileName.xls");


//        $tab = "\t";
//        $br = "\n";
//        $head = array('ID', '姓名', '学号', '分数');
        $head = ['ID', '姓名', '学号', '分数'
        ];


        fputcsv($fp, $head);
        // //输出内容如下：
//        echo $head . $br;

        // 获取试卷的某个题目的id
        $answer_id = \think\Db::name('article_contens')
            ->where('cate', $article_id)
            ->value('id');


        $answer_list = \think\Db::name('answer')
            ->where('cate', $article_id)
            ->where('answerid', $answer_id)
            ->order('id desc')
            ->select();


        foreach ($answer_list as $key => $answer_user) {

            // 根据答题人姓名，获取每个题目的回答和得分
            $answer_list_user = \think\Db::name('answer')
                ->where('name', $answer_user['name'])
                ->select();

            $answer_list[$key]['answer_list'] = $answer_list_user;

            // 查询并获取某个字段的总和
            $total_score = \think\Db::name('answer')->where('name', $answer_user['name'])->sum('score');

            $answer_list[$key]['total_score'] = $total_score;

            $row = [
                $answer_user['id'],
                $answer_user['member'],
                $answer_user['serialnumber'],
                $total_score
            ];
            fputcsv($fp, $row);
//
//            echo $answer_user['id'] . $tab;
//            echo $answer_user['member'] . $tab;
//            echo $answer_user['serialnumber'] . $tab;
//            echo $total_score . $tab;
//            echo $br;


        }


        //var_dump($cateres);
        // 获取数据集记录数
//        $count = count($cateres);
        // 遍历数据集
//        foreach ($cateres as $user) {
//            echo $user['id'] . $tab;
//            echo $user['score'] . $tab;
//            echo $br;
//        }


    }

    public function single()
    {
        // 接收外部传入数值的部分
        $id = input('artid');
        $school = input('school');
        $city = input('city');
        $area = input('area');
        $tomdown = input('d');

        $export = 'artid=' . $id . '&school=' . $school . '&city=' . $city . '&area=' . $area . '&d=' . 1;


        $this->assign('export', $export);

        // 查询题目
        $article_contens = \think\Db::name('article_contens')
            ->where('cate', $id)
            ->order('id')
            ->where('title', 'neq', ' ')
            ->select();

        //      关于导出文件的生成和自动下载
        if ($tomdown >= 1) {
            $filename = time();
//          dump($article_contens);

            header("content-type:text/html; charset=utf-8");
            $file = fopen("f-$filename.csv", "w");

//          $line = array(1,'学习—中文乱码',12345,'vb200',iconv("UTF-8", "GB2312//IGNORE", "学习—中文乱码"));
            $title = array('ID', '编号', '问卷题目', 'vb200', '问卷选项');

//            这里是获取字段的名字
            $title = array_keys($article_contens['0']);
            $line = $article_contens;

            //提前设置一个数组，设置导出后标题
            foreach ($title as &$value) {
                $value = iconv("UTF-8", "GB2312//IGNORE", "$value");
            }
            fputcsv($file, $title);
            // 可以去掉某些不需要的数组。
            foreach ($line as $value) {
                foreach ($value as &$valuevalue) {
//                    foreach ($valuevalue as &$s){
                    echo($valuevalue);
//                        echo "$valuevalue <br>";
                    $valuevalue = iconv("UTF-8", "GB2312//IGNORE", "$valuevalue");
//                    die();

//                    }

                }
//                注意这一句的放置位置
                fputcsv($file, $value);
            }

        }


        // 循环读取所有问题
        for ($a = 0; $a < count($article_contens); $a++) {

            $honey = 0;
            for ($i = 1; $i < 7; $i++) {
                $arid = $i - 1;

                if ($school) {
                    # code...
                    $count = \think\Db::name('answer')
                        ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                        ->where('a.cate', $id)
                        ->where('c.school', $school)
                        ->where('a.answerid', $article_contens[$a]['id'])
                        ->sum('a.answer' . $i);
                } elseif ($city) {
                    # code...
                    $count = \think\Db::name('answer')
                        ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                        ->where('a.cate', $id)
                        ->where('c.city', $city)
                        ->where('a.answerid', $article_contens[$a]['id'])
                        ->sum('a.answer' . $i);

                } elseif ($area) {
                    # code...
                    $count = \think\Db::name('answer')
                        ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                        ->where('a.cate', $id)
                        ->where('c.area', $area)
                        ->where('a.answerid', $article_contens[$a]['id'])
                        ->sum('a.answer' . $i);

                } else {
                    # code...
                    $count = \think\Db::name('answer')
                        ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                        ->where('a.cate', $id)
                        ->where('a.answerid', $article_contens[$a]['id'])
                        ->sum('a.answer' . $i);


                }


                $a1 = $a + 1;
                $article_contens[$a]['checked' . $i] = $count;


                $honey = $honey + $count;
                $son = $i;
                if ($son >= 6) {
                    for ($s = 1; $s < 7; $s++) {
                        if ($honey <= 0) {

                            $article_contens[$a]['checked_son' . $s] = 0;
                        } else {


                            $article_contens[$a]['checked_son' . $s] = round($article_contens[$a]['checked' . $s] / $honey * 100);
                        }
                    }

                }

            }


        }


        // 查询题目？
        $arts = \think\Db::name('article')->alias('a')->join('cate c', 'c.id = a.cateid', 'LEFT')->field('a.title,a.desc,a.time,a.click,a.close,a.id,a.cateid,c.catename')->where('a.id', $id)->find();

        //  查询总条数
        if ($school) {
            $answer_count = \think\Db::name('answer')
                ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                ->where('a.cate', $id)
                ->where('c.school', $school)
                ->where('a.answerid', $article_contens[0]['id'])
                ->count('a.id');
        } elseif ($city) {
            $answer_count = \think\Db::name('answer')
                ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                ->where('a.cate', $id)
                ->where('c.city', $city)
                ->where('a.answerid', $article_contens[0]['id'])
                ->count('a.id');

        } elseif ($area) {
            $answer_count = \think\Db::name('answer')
                ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                ->where('a.cate', $id)
                ->where('c.area', $area)
                ->where('a.answerid', $article_contens[0]['id'])
                ->count('a.id');

        } else {
            $answer_count = \think\Db::name('answer')
                ->alias('a')->join('member c', 'c.id = a.memberid', 'LEFT')
                ->where('a.cate', $id)
                ->where('a.answerid', $article_contens[0]['id'])
                ->count('a.id');
        }


        $this->assign('arts', $arts);
        $this->assign('answer_count', $answer_count);
        $this->assign('article_contens', $article_contens);

        return $this->fetch('single');
    }


}
